package com.wang.back.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.common.pojo.BasePojoEnum;
import com.wang.common.pojo.BaseQuery;
import com.wang.common.util.ConstatFinalUtil;
import com.wang.common.web.controller.BaseController;
import com.wang.demo.pojo.AtDemoDynasty;
import com.wang.demo.pojo.AtDemoDynastyQuery;
import com.wang.demo.pojo.AtDemoKing;
import com.wang.demo.pojo.AtDemoKingQuery;
import com.wang.demo.service.AtDemoDynastyService;
import com.wang.demo.service.AtDemoKingService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 示例的Controller
 * @author ZjxMi
 */
@Controller
@RequestMapping("/back/demo")
@Log4j2
public class DemoBackController extends BaseController {
    @Autowired
    private AtDemoDynastyService demoDynastyService;
    @Autowired
    private AtDemoKingService demoKingService;

    /**
     * 朝代查询多条
     * @return
     */
    @RequestMapping("/dynastyList")
    public String dynastyList(AtDemoDynastyQuery paramQuery, Model model){
        log.info("==朝代列表==");
        /* 分页对象 */
        IPage<AtDemoDynasty> paramPage = null;
        try {
            paramPage = new Page<>(paramQuery.getCurrent(), paramQuery.getSize());
        } catch (Exception e) {
            paramPage = new Page<>(1, 20);
        }
        /* 时间处理 */
        if (StringUtils.isNotEmpty(paramQuery.getStDate())) {
            paramQuery.setPubTimeSt(this.dateUtil.strToDateTime(paramQuery.getStDate()));
        }
        if (StringUtils.isNotEmpty(paramQuery.getEdDate())) {
            paramQuery.setPubTimeEd(this.dateUtil.strToDateTime(paramQuery.getEdDate()));
        }
        paramQuery.addLike();
        /* 查询对象 */
        List<AtDemoDynasty> dataList = this.demoDynastyService.findList(paramPage, paramQuery);
        paramQuery.removeLike();
        /* 列表数据 */
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_DATALIST, dataList);
        /* 分页数据 */
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PAGEINFOUTIL, paramPage);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PARAMQUERY, paramQuery);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ENUMSONE, new AtDemoDynasty());
        /* 查询数据 */
        return "/back/demo/dynastyList";
    }

    /**
     * 朝代打开添加页面
     * @return
     */
    @RequestMapping("/dynastyInsert")
    public String dynastyInsert(AtDemoDynastyQuery paramQuery, Model model){
        log.info("==朝代添加==");
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ONE, new AtDemoDynasty());
        /* 查询数据 */
        return "/back/demo/dynastyInsert";
    }

    /**
     * 朝代添加提交操作
     * @return
     */
    @RequestMapping("/dynastyInsertSubmit")
    @ResponseBody
    public String dynastyInsertSubmit(AtDemoDynastyQuery paramQuery, Model model){
        log.info("==朝代添加提交==");
        boolean dbFlag = this.demoDynastyService.save(paramQuery.getEntity());
        JSONObject resultJson = this.proccedResponseJson(dbFlag);
        /* 返回json给客户端 */
        return resultJson.toJSONString();
    }

    /**
     * 朝代打开更新页面
     * 更新和详情是同一个页面;
     * @return
     */
    @RequestMapping("/dynastyUpdate")
    public String dynastyUpdate(AtDemoDynastyQuery paramQuery, Model model){
        log.info("==朝代更新==");
        /* 根据id查询 */
        AtDemoDynasty one = this.demoDynastyService.findOne(paramQuery);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ONE, one);

        if (BaseQuery.FINAL_OPER_UPDATE.equalsIgnoreCase(paramQuery.getOperType())) {
            /* 查询数据 */
            return "/back/demo/dynastyUpdate";
        }
        /* 查询数据 */
        return "/back/demo/dynastyInfo";
    }

    /**
     * 朝代更新提交操作
     * <pre>
     * 朝代表有10个字段,用户填写的只有5个字段;
     * 更新的时候只更新5个字段;剩下的5个字段不用更新
     * 千万不要把页面中传的参数SpringMVC会自动创建对象,这个对象不要直接更新数据库,很危险;
     * </pre>
     * @return
     */
    @RequestMapping("/dynastyUpdateSubmit")
    @ResponseBody
    public String dynastyUpdateSubmit(AtDemoDynastyQuery paramQuery, Model model){
        log.info("==朝代更新提交==");
        AtDemoDynasty entity = paramQuery.getEntity();
        if (StringUtils.isNotEmpty(paramQuery.getPubTime())) {
            entity.setPubTime(this.dateUtil.strToDateTime(paramQuery.getPubTime()));
        }
        boolean dbFlag = this.demoDynastyService.updateById(entity);
        JSONObject resultJson = this.proccedResponseJson(dbFlag);
        /* 返回json给客户端 */
        return resultJson.toJSONString();
    }

    /**
     * 朝代打开添加页面
     * @return
     */
    @RequestMapping("/dynastyBatch")
    @ResponseBody
    public String dynastyBatch(AtDemoDynastyQuery paramQuery, Model model){
        log.info("==朝代批量提交==");
        String operType = paramQuery.getOperType();
        String[] ids = paramQuery.getIds();
        String info = ConstatFinalUtil.FINAL_OPER_SUCCESS;
        int totalCount = 0;
        int succedCount = 0;
        int failedCount = 0;
        if (StringUtils.isNotEmpty(operType)) {
            if (Objects.nonNull(ids) && ids.length > 0) {
                totalCount = ids.length;
                for (String idTemp : ids) {
                    try {
                        AtDemoDynastyQuery paramQueryTemp = new AtDemoDynastyQuery();
                        AtDemoDynasty entity = paramQueryTemp.getEntity();
                        entity.setId(idTemp);
                        /* 根据id查询每一个 记录对象 */
                        AtDemoDynasty dataDbResult = this.demoDynastyService.findOne(paramQueryTemp);
                        if (dataDbResult != null) {
                            boolean dbFlag = false;
                            if (BasePojoEnum.OPERTYPE_DELETE.getCode().equalsIgnoreCase(operType)) {
                                /* 删除 */
                                dbFlag = this.demoDynastyService.removeById(idTemp);
                            } else if (BasePojoEnum.OPERTYPE_RESTORE.getCode().equalsIgnoreCase(operType)) {
                                /* 还原,为什么这里面要传这么多参数,一切的一切就是为了在xml中拼装sql语句 */
                                paramQueryTemp = new AtDemoDynastyQuery();
                                entity = paramQueryTemp.getEntity();
                                entity.setDelFlag(BasePojoEnum.DELFLAG_YES.getCode());
                                entity.setId(idTemp);
                                paramQueryTemp.setOperType(BasePojoEnum.OPERTYPE_RESTORE.getCode());
                                dbFlag = this.demoDynastyService.updateBatch(paramQueryTemp) > 0 ;
                            } else if (BasePojoEnum.OPERTYPE_EMPTY.getCode().equalsIgnoreCase(operType)) {
                                /* 清空 */
                                paramQueryTemp = new AtDemoDynastyQuery();
                                entity = paramQueryTemp.getEntity();
                                entity.setId(idTemp);
                                dbFlag = this.demoDynastyService.deleteBatch(paramQueryTemp) > 0 ;
                            } else if (BasePojoEnum.OPERTYPE_UPDATESTATUS.getCode().equalsIgnoreCase(operType)) {
                                /* 批量修改状态 */
                                dataDbResult.setStatus(paramQuery.getEntity().getStatus());
                                dbFlag = this.demoDynastyService.updateById(dataDbResult);
                            }
                            if (dbFlag) {
                                succedCount ++;
                            } else {
                                failedCount ++;
                            }
                        }
                    } catch (Exception e) {
                        log.error("批量操作失败了,id:{}", idTemp, e);
                        failedCount ++;
                    }
                }
            } else {
                /* 未选择类型,ids */
                info = "ids为空";
            }
        } else {
            /* 操作类型未选择 */
            info = "操作类型未选择";
        }

        String messInfo = "批量操作日志:提示信息:${info}, 总条数:${totalCount},成功条数:${succedCount},失败条数:${failedCount}";
        Map<String,String> paramsMap = new HashMap<>(1);
        paramsMap.put("info", info);
        paramsMap.put("totalCount", String.valueOf(totalCount));
        paramsMap.put("succedCount", String.valueOf(succedCount));
        paramsMap.put("failedCount", String.valueOf(failedCount));
        messInfo = this.regexUtil.replaceOperator(messInfo, paramsMap);

        paramsMap = new HashMap<>(1);
        paramsMap.put(ConstatFinalUtil.FINAL_CONFIG_INFO_SUCCESS_PARAM1, messInfo);
        /* 查询数据 */
        JSONObject resultJson = this.proccedResponseJson(ConstatFinalUtil.FINAL_OPER_SUCCESS.equalsIgnoreCase(info), paramsMap);
        log.info("==结果:{}==", resultJson);
        return resultJson.toJSONString();
    }

    /**
     * 皇上查询多条
     * @return
     */
    @RequestMapping("/kingList")
    public String kingList(AtDemoKingQuery paramQuery, Model model){
        log.info("==皇上列表==");
        /* 分页对象 */
        IPage<AtDemoKing> paramPage = null;
        try {
            paramPage = new Page<>(paramQuery.getCurrent(), paramQuery.getSize());
        } catch (Exception e) {
            paramPage = new Page<>(1, 20);
        }
        /* 时间处理 */
        if (StringUtils.isNotEmpty(paramQuery.getStDate())) {
            paramQuery.setPubTimeSt(this.dateUtil.strToDateTime(paramQuery.getStDate()));
        }
        if (StringUtils.isNotEmpty(paramQuery.getEdDate())) {
            paramQuery.setPubTimeEd(this.dateUtil.strToDateTime(paramQuery.getEdDate()));
        }
        paramQuery.addLike();
        /* 查询对象 */
        List<AtDemoKing> dataList = this.demoKingService.findList(paramPage, paramQuery);
        paramQuery.removeLike();
        /* 列表数据 */
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_DATALIST, dataList);
        /* 分页数据 */
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PAGEINFOUTIL, paramPage);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PARAMQUERY, paramQuery);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ENUMSONE, new AtDemoKing());

        /* 搜索条件;根据朝代查询皇上 */
        AtDemoDynastyQuery dynastyQuery = new AtDemoDynastyQuery();
        AtDemoDynasty entity = dynastyQuery.getEntity();
        entity.setStatus(BasePojoEnum.STATUS_ENABLE.getCode());
        entity.setDelFlag(BasePojoEnum.DELFLAG_YES.getCode());
        List<AtDemoDynasty> dynastyList = this.demoDynastyService.findList(null, dynastyQuery);
        model.addAttribute("dynastyList", dynastyList);
        /* 查询数据 */
        return "/back/demo/kingList";
    }

    /**
     * 皇上打开添加页面
     * @return
     */
    @RequestMapping("/kingInsert")
    public String kingInsert(AtDemoKingQuery paramQuery, Model model){
        log.info("==皇上添加==");
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ONE, new AtDemoKing());

        /* 搜索条件;根据朝代查询皇上 */
        AtDemoDynastyQuery dynastyQuery = new AtDemoDynastyQuery();
        AtDemoDynasty entity = dynastyQuery.getEntity();
        entity.setStatus(BasePojoEnum.STATUS_ENABLE.getCode());
        entity.setDelFlag(BasePojoEnum.DELFLAG_YES.getCode());
        List<AtDemoDynasty> dynastyList = this.demoDynastyService.findList(null, dynastyQuery);
        model.addAttribute("dynastyList", dynastyList);
        /* 查询数据 */
        return "/back/demo/kingInsert";
    }

    /**
     * 皇上添加提交操作
     * @return
     */
    @RequestMapping("/kingInsertSubmit")
    @ResponseBody
    public String kingInsertSubmit(AtDemoKingQuery paramQuery, Model model){
        log.info("==皇上添加==");
        boolean dbFlag = this.demoKingService.save(paramQuery.getEntity());
        JSONObject resultJson = this.proccedResponseJson(dbFlag);
        /* 返回json给客户端 */
        return resultJson.toJSONString();
    }

    /**
     * 皇上打开更新页面
     * 更新和详情是同一个页面;
     * @return
     */
    @RequestMapping("/kingUpdate")
    public String kingUpdate(AtDemoKingQuery paramQuery, Model model){
        log.info("==皇上更新==");
        /* 根据id查询 */
        AtDemoKing one = this.demoKingService.findOne(paramQuery);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ONE, one);

        if (BaseQuery.FINAL_OPER_UPDATE.equalsIgnoreCase(paramQuery.getOperType())) {
            /* 搜索条件;根据朝代查询皇上 */
            AtDemoDynastyQuery dynastyQuery = new AtDemoDynastyQuery();
            AtDemoDynasty entity = dynastyQuery.getEntity();
            entity.setStatus(BasePojoEnum.STATUS_ENABLE.getCode());
            entity.setDelFlag(BasePojoEnum.DELFLAG_YES.getCode());
            List<AtDemoDynasty> dynastyList = this.demoDynastyService.findList(null, dynastyQuery);
            model.addAttribute("dynastyList", dynastyList);
            /* 查询数据 */
            return "/back/demo/kingUpdate";
        }
        /* 查询数据 */
        return "/back/demo/kingInfo";
    }

    /**
     * 皇上更新提交操作
     * <pre>
     * 皇上表有10个字段,用户填写的只有5个字段;
     * 更新的时候只更新5个字段;剩下的5个字段不用更新
     * 千万不要把页面中传的参数SpringMVC会自动创建对象,这个对象不要直接更新数据库,很危险;
     * </pre>
     * @return
     */
    @RequestMapping("/kingUpdateSubmit")
    @ResponseBody
    public String kingUpdateSubmit(AtDemoKingQuery paramQuery, Model model){
        log.info("==皇上更新提交==");
        boolean dbFlag = this.demoKingService.updateById(paramQuery.getEntity());
        JSONObject resultJson = this.proccedResponseJson(dbFlag);
        /* 返回json给客户端 */
        return resultJson.toJSONString();
    }

    /**
     * 皇上打开添加页面
     * @return
     */
    @RequestMapping("/kingBatch")
    @ResponseBody
    public String kingBatch(AtDemoKingQuery paramQuery, Model model){
        log.info("==皇上批量提交==");
        String operType = paramQuery.getOperType();
        String[] ids = paramQuery.getIds();
        String info = ConstatFinalUtil.FINAL_OPER_SUCCESS;
        int totalCount = 0;
        int succedCount = 0;
        int failedCount = 0;
        if (StringUtils.isNotEmpty(operType)) {
            if (Objects.nonNull(ids) && ids.length > 0) {
                totalCount = ids.length;
                for (String idTemp : ids) {
                    try {
                        AtDemoKingQuery paramQueryTemp = new AtDemoKingQuery();
                        AtDemoKing entity = paramQueryTemp.getEntity();
                        entity.setId(idTemp);
                        /* 根据id查询每一个 记录对象 */
                        AtDemoKing dataDbResult = this.demoKingService.findOne(paramQueryTemp);
                        if (dataDbResult != null) {
                            boolean dbFlag = false;
                            if (BasePojoEnum.OPERTYPE_DELETE.getCode().equalsIgnoreCase(operType)) {
                                /* 删除 */
                                dbFlag = this.demoKingService.removeById(idTemp);
                            } else if (BasePojoEnum.OPERTYPE_RESTORE.getCode().equalsIgnoreCase(operType)) {
                                /* 还原,为什么这里面要传这么多参数,一切的一切就是为了在xml中拼装sql语句 */
                                paramQueryTemp = new AtDemoKingQuery();
                                entity = paramQueryTemp.getEntity();
                                entity.setDelFlag(BasePojoEnum.DELFLAG_YES.getCode());
                                entity.setId(idTemp);
                                paramQueryTemp.setOperType(BasePojoEnum.OPERTYPE_RESTORE.getCode());
                                dbFlag = this.demoKingService.updateBatch(paramQueryTemp) > 0 ;
                            } else if (BasePojoEnum.OPERTYPE_EMPTY.getCode().equalsIgnoreCase(operType)) {
                                /* 清空 */
                                paramQueryTemp = new AtDemoKingQuery();
                                entity = paramQueryTemp.getEntity();
                                entity.setId(idTemp);
                                dbFlag = this.demoKingService.deleteBatch(paramQueryTemp) > 0 ;
                            } else if (BasePojoEnum.OPERTYPE_UPDATESTATUS.getCode().equalsIgnoreCase(operType)) {
                                /* 批量修改状态 */
                                dataDbResult.setStatus(paramQuery.getEntity().getStatus());
                                dbFlag = this.demoKingService.updateById(dataDbResult);
                            }
                            if (dbFlag) {
                                succedCount ++;
                            } else {
                                failedCount ++;
                            }
                        }
                    } catch (Exception e) {
                        log.error("批量操作失败了,id:{}", idTemp, e);
                        failedCount ++;
                    }
                }
            } else {
                /* 未选择类型,ids */
                info = "ids为空";
            }
        } else {
            /* 操作类型未选择 */
            info = "操作类型未选择";
        }

        String messInfo = "批量操作日志:提示信息:${info}, 总条数:${totalCount},成功条数:${succedCount},失败条数:${failedCount}";
        Map<String,String> paramsMap = new HashMap<>(1);
        paramsMap.put("info", info);
        paramsMap.put("totalCount", String.valueOf(totalCount));
        paramsMap.put("succedCount", String.valueOf(succedCount));
        paramsMap.put("failedCount", String.valueOf(failedCount));
        messInfo = this.regexUtil.replaceOperator(messInfo, paramsMap);

        paramsMap = new HashMap<>(1);
        paramsMap.put(ConstatFinalUtil.FINAL_CONFIG_INFO_SUCCESS_PARAM1, messInfo);
        /* 查询数据 */
        JSONObject resultJson = this.proccedResponseJson(ConstatFinalUtil.FINAL_OPER_SUCCESS.equalsIgnoreCase(info), paramsMap);
        log.info("==结果:{}==", resultJson);
        return resultJson.toJSONString();
    }
}
